<?php
namespace App\Http\Model;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Http\Request;
use App\Http\Constant;
use Illuminate\Support\Facades\DB;

class RbacRole extends Model{
	protected $table = 'rbac_role';
	protected $primaryKey = 'id';

	public function createRole(Request $request){
		$exist_role = $this->where('role_name', '=', $request->input('name'))->get()->toArray();
		if(0 !== count($exist_role)){
			throw new \Exception('Rbac role [name='.$request->input('name').'] exists.', Constant::EC_RBAC_ROLE_EXISTS);
		}else{
			$this->role_name = $request->input('name');
			$this->status = Constant::TFEX_RBAC_ROLE_STATUS_OPEN;
			$this->save();
			return $this->id;
		}
	}

	public function toggleRbacRoleStatus($role_ids=[], $role_status=1){
		//return $this->whereIn('id', $role_ids)->update(['status' => $role_status]) !== false;
                return $this->whereIn('id', $role_ids)->delete() !== false;
	}
        
        //判断此角色名称是否存在
        public function isExsitsRoleName(Request $request){
            $exist_role = $this->where('role_name', '=', $request->input('name'))->get()->toArray();
            if(0 !== count($exist_role)){
                return 1;
            }
            return 0;
        }
        
        //删除角色的时候判断该角色是否有用户在用
        public function delRoleByIds($role_ids=[]){
            //实例化模型
            $rbac_user_model = new RbacUser();
            
            //根据角色id获取角色下面所属的用户
            $exist_user = $rbac_user_model->whereIn('role_id', $role_ids)->get()->toArray();
            if(0 !== count($exist_user)){
                return 1;
            }
            return 0;
        }
}